<template>
  <div class="container">
    <h1>Git 提交历史修改工具</h1>

    <!-- Git 仓库配置 -->
    <div class="section">
      <h2>仓库配置</h2>
      <div class="input-group">
        <input v-model="gitConfig.url" placeholder="Git 仓库 URL" type="url" />
        <input v-model="gitConfig.username" placeholder="用户名" />
        <input v-model="gitConfig.password" placeholder="密码/Token" type="password" />
      </div>
      <button @click="cloneRepository" :disabled="!gitConfig.url">克隆仓库</button>
      <button @click="selectLocalRepository">选择本地仓库</button>
    </div>

    <!-- 提交历史 -->
    <div class="section" v-if="commitHistory.length > 0">
      <h2>提交历史</h2>
      <div class="tool-bar">
        <div class="history-controls">
            <button @click="exportHistory">导出历史</button>
            <button @click="loadHistory">刷新历史</button>
            <input v-model="historyLimit" type="number" placeholder="显示数量" />

          </div>
          <div class="change-time-box">
            <label>修改选中日期：</label>
            <el-input-number  v-model="incrDays" placeholder="加减天数"></el-input-number>

            <button @click="modifyDays" >应用选中记录</button>
            <button @click="resetDate" >重置</button>
          </div>
      </div>


      <div class="commit-list">
        <div
          v-for="commit in commitHistory"
          :key="commit.hash"
          class="commit-item"
          :class="{ selected: selectedCommits.includes(commit) }"
          @click="toggleCommit(commit)"
        >
          <div class="commit-author-icon" :style="{background:iconColor(commit.author)}">
            {{ commit.author.substring(0,1).toUpperCase() }}
          </div>
          <div class="commit-header">
            <span class="commit-hash">{{ commit.hash.substring(0, 8) }}</span>
            <span class="commit-author">{{ commit.author }} &lt;{{ commit.email }}&gt;</span>
            <span class="commit-date">
              <el-date-picker
                v-model="commit.date"
                type="datetime"
                placeholder="Select date and time"
              />


            </span>
          </div>
          <div class="commit-message">{{ commit.message }}</div>
          <div class="commit-body" v-if="commit.body">{{ commit.body }}</div>
        </div>
      </div>
    </div>

    <!-- 修改提交 -->
    <div class="section" v-if="selectedCommits.length > 0">
      <h2>修改选中的提交 ({{ selectedCommits.length }})</h2>
      <div class="modify-form">
        <div class="input-group">
          <input v-model="modifyAuthor.name" placeholder="新作者姓名" />
          <input v-model="modifyAuthor.email" placeholder="新作者邮箱" type="email" />
        </div>
        <!-- <textarea
          v-model="modifyMessage"
          placeholder="新的提交消息（可选，留空保持原消息）"
          rows="3"
        ></textarea> -->
        <button @click="modifySelectedCommits" class="modify-btn">修改提交</button>
      </div>
    </div>

    <!-- 推送更改 -->
    <div class="section" v-if="hasModifications">
      <h2>推送更改</h2>
      <button @click="pushChanges" class="push-btn">推送修改到远程仓库</button>
      <p class="warning">警告：修改历史提交后需要强制推送，这可能会影响其他协作者！</p>
    </div>

    <!-- 状态信息 -->
    <div class="status" :class="statusType" v-if="statusMessage">
      {{ statusMessage }}
    </div>
  </div>
</template>

<script  setup>
import { ref, reactive, toRaw, watch, onMounted, computed } from 'vue';
import * as XLSX from 'xlsx';
import DateUtil from '@/framework/date-util'


const gitConfig = reactive({
  url: '',
  username: localStorage.getItem('username'),
  password: localStorage.getItem('password')
});

const commitHistory = ref([]);
const selectedCommits = ref([]);
const historyLimit = ref(1000);
const currentRepoPath = ref('');
const hasModifications = ref(false);
const incrDays = ref(0)

const modifyAuthor = reactive({
  name: '',
  email: ''
});

//const modifyMessage = ref('');
const statusMessage = ref('');
const statusType = ref('info');

// 克隆仓库
const cloneRepository = async () => {
  try {
    statusMessage.value = '正在克隆仓库...';
    statusType.value = 'info';

    const result = await window.gitApi.cloneRepository(
      gitConfig.url,
      gitConfig.username,
      gitConfig.password
    );

    if (result.success) {
      currentRepoPath.value = result.path;
      statusMessage.value = `仓库克隆成功: ${result.path}`;
      statusType.value = 'success';
      await loadHistory();
    } else {
      statusMessage.value = `克隆失败: ${result.error}`;
      statusType.value = 'error';
    }
  } catch (error) {
    statusMessage.value = `发生错误: ${error.message}`;
    statusType.value = 'error';
  }
};

// 选择本地仓库
const selectLocalRepository = async () => {
  try {
    const result = await window.gitApi.selectDirectory();
    if (result.success) {
      currentRepoPath.value = result.path;
      statusMessage.value = `已选择仓库: ${result.path}`;
      statusType.value = 'success';
      await loadHistory();
    }
  } catch (error) {
    statusMessage.value = `选择目录失败: ${error.message}`;
    statusType.value = 'error';
  }
};

const exportHistory = async() => {

  if (!currentRepoPath.value) return;

  try {
    statusMessage.value = '正在加载提交历史...';
    const result = await window.gitApi.getCommitHistory(
      currentRepoPath.value,
      historyLimit.value
    );

    if (result.success) {
      statusType.value = 'success';
      statusMessage.value = '';
      let history = result.history;
      let data = [['NAME','CONTENT','DATE']]

      history.forEach(item => {
        const date = DateUtil.toDate(item.date);
        console.log(date);
        data.push([item.author, item.message, DateUtil.format(date, 'yyyy-MM-dd HH:mm:ss')])
      })

      // 将数据转换为工作表
      const ws = XLSX.utils.aoa_to_sheet(data);

      // 创建工作簿并添加工作表
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "工作记录");

      // 导出Excel文件
      XLSX.writeFile(wb, '项目记录.xlsx');



    } else {
      statusMessage.value = `加载历史失败: ${result.error}`;
      statusType.value = 'error';
    }
  } catch (error) {
    statusMessage.value = `发生错误: ${error.message}`;
    statusType.value = 'error';
  }


}

// 加载提交历史
const loadHistory = async () => {
  if (!currentRepoPath.value) return;

  try {
    statusMessage.value = '正在加载提交历史...';
    const result = await window.gitApi.getCommitHistory(
      currentRepoPath.value,
      historyLimit.value
    );

    if (result.success) {

      commitHistory.value = result.history.map((item,index)=>{
        return {
          index: index,
          originalDate: item.date,
          ...item
        }
      });
      statusMessage.value = `加载了 ${result.history.length} 条提交记录`;
      statusType.value = 'success';
    } else {
      statusMessage.value = `加载历史失败: ${result.error}`;
      statusType.value = 'error';
    }
  } catch (error) {
    statusMessage.value = `发生错误: ${error.message}`;
    statusType.value = 'error';
  }
};

// 选择/取消选择提交
const toggleCommit = (commit) => {
  const index = selectedCommits.value.indexOf(commit);
  if (index > -1) {
    selectedCommits.value.splice(index, 1);
  } else {
    selectedCommits.value.push(commit);
  }
};

const modifyDays = async () => {
  if (selectedCommits.value.length === 0) {
    statusMessage.value = '请先选择要修改的记录';
    statusType.value = 'error';
    return;
  }
  if(!incrDays.value){
    statusMessage.value = '请输入要加减的天数';
    statusType.value = 'error';
    return;
  }

  const commites = selectedCommits.value;
  commites.forEach(item => {
    item.date = addDays(item.originalDate, incrDays.value);
  })
}

const resetDate = async () => {
  if (selectedCommits.value.length === 0) {
    statusMessage.value = '请先选择要重置的记录';
    statusType.value = 'error';
    return;
  }
  incrDays.value = 0;

  const commites = selectedCommits.value;
  commites.forEach(item => {
    item.date = item.originalDate;
  })
}



// 修改选中的提交
const modifySelectedCommits = async () => {
  if (selectedCommits.value.length === 0) {
    statusMessage.value = '请先选择要修改的提交';
    statusType.value = 'error';
    return;
  }

  if (!incrDays.value && (!modifyAuthor.name || !modifyAuthor.email)) {
    statusMessage.value = '请填写作者姓名和邮箱';
    statusType.value = 'error';
    return;
  }

  try {

    const commites = selectedCommits.value;
    if(modifyAuthor.name){
        commites.forEach(item => {
          item.author = modifyAuthor.name;
        })
    }
    if(modifyAuthor.email){
        commites.forEach(item => {
          item.email = modifyAuthor.email;
        })
    }


    commites.sort((a, b) => a.index > b.index ? 1: -1);


    const commitList = commites.map(commint=> {
      const item = toRaw(commint);
      item.date = new Date(item.date).toISOString()
      return item;
    });




    statusMessage.value = '正在修改提交...';
    const result = await window.gitApi.modifyCommits(
      currentRepoPath.value,
      commitList
    );

    if (result.success) {
      statusMessage.value = `成功修改了 ${result.results.filter(r => r.success).length} 个提交`;
      statusType.value = 'success';
      hasModifications.value = true;

      // 重新加载历史
      await loadHistory();
      selectedCommits.value = [];
    } else {
      statusMessage.value = `修改失败: ${result.error}`;
      statusType.value = 'error';
    }


  } catch (error) {
    statusMessage.value = `发生错误: ${error.message}`;
    statusType.value = 'error';
  }

};

// 推送更改
const pushChanges = async () => {
  if (!gitConfig.username || !gitConfig.password) {
    statusMessage.value = '请提供用户名和密码进行推送';
    statusType.value = 'error';
    return;
  }

  try {
    statusMessage.value = '正在推送更改...';

    const result = await window.gitApi.pushChanges(
      currentRepoPath.value,
      gitConfig.username,
      gitConfig.password
    );

    if (result.success) {
      statusMessage.value = '更改推送成功';
      statusType.value = 'success';
      hasModifications.value = false;
    } else {
      statusMessage.value = `推送失败: ${result.error}`;
      statusType.value = 'error';
    }
  } catch (error) {
    statusMessage.value = `发生错误: ${error.message}`;
    statusType.value = 'error';
  }
};

// 工具函数
const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString();
};

const addDays = (date, days) => {
  let newDate = new Date(date);
  newDate.setDate(newDate.getDate() + days);
  return newDate;
};

const iconColor = computed(() => {
  const colours = [
					"#1abc9c", "#2ecc71", "#3498db", "#9b59b6", "#34495e", "#16a085", "#27ae60", "#2980b9", "#8e44ad", "#2c3e50",
					"#f1c40f", "#e67e22", "#e74c3c", "#ecf0f1", "#95a5a6", "#f39c12", "#d35400", "#c0392b", "#bdc3c7", "#7f8c8d"
				];
  return (text) =>{
      const nameSplit = String(text).toUpperCase().split(' ');
      let initials = 0;
      if (nameSplit.length == 1) {
				initials = nameSplit[0] ? nameSplit[0].charAt(0):'?';
			} else {
				initials = nameSplit[0].charAt(0) + nameSplit[1].charAt(0);
			}
      const charIndex     = (initials == '?' ? 72 : initials.charCodeAt(0)) - 64;
			const colourIndex   = charIndex % 20;

      return colours[colourIndex - 1]
    }
})

onMounted(() => {
  // 可以在这里加载一些默认配置
});

watch(() => gitConfig.username, (newVal) => {
  if(newVal){
    localStorage.setItem('username', newVal);
  }
})

watch(() => gitConfig.password, (newVal) => {
  if(newVal){
    localStorage.setItem('password', newVal);
  }
})

</script>

<style scoped>
.container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  height: 100%;
}

.section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.input-group {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.input-group input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

button {
  padding: 8px 16px;
  margin-right: 10px;
  background: #007acc;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.modify-btn {
  background: #28a745;
}

.push-btn {
  background: #dc3545;
}

.commit-list {
  max-height: 400px;
  overflow-y: auto;
}

.commit-item {
  padding: 10px 10px 10px 56px;
  border: 1px solid #eee;
  margin-bottom: 5px;
  border-radius: 4px;
  cursor: pointer;
  position: relative;

}

.commit-author-icon{
  position: absolute;
  left: 10px;
  width: 36px;
  height: 36px;
  color: #ffffff;
  font-size: 20px;
  text-align: center;
  line-height: 36px;
  border-radius:50%;
}

.commit-item.selected {
  background: #e3f2fd;
  border-color: #2196f3;
}

.commit-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
  font-size: 12px;
}

.commit-hash {
  font-family: monospace;
  color: #666;
}

.commit-author {
  flex: 1;
  margin: 0 10px;
}

.commit-date {
  color: #999;
}

.commit-message {
  font-weight: bold;
  margin-bottom: 5px;
}

.commit-body {
  font-size: 12px;
  color: #666;
  white-space: pre-wrap;
}

.modify-form textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-bottom: 10px;
  resize: vertical;
}

.status {
  padding: 10px;
  border-radius: 4px;
  margin-top: 20px;
}

.status.info {
  background: #d1ecf1;
  color: #0c5460;
}

.status.success {
  background: #d4edda;
  color: #155724;
}

.status.error {
  background: #f8d7da;
  color: #721c24;
}

.warning {
  color: #856404;
  background: #fff3cd;
  padding: 10px;
  border-radius: 4px;
  margin-top: 10px;
}

.tool-bar{
  display: flex;
  justify-content: space-between;
}

.history-controls {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.history-controls input {
  width: 100px;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
}
.change-time-box {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
  align-items: center;
}

.change-time-box input {
  width: 100px;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
}
</style>
